import Taro from '@tarojs/taro';
import { useState, useEffect } from "react";
import { View, Radio, RadioGroup, Button } from '@tarojs/components';
import { AtInput, AtForm, AtImagePicker, AtTextarea, AtMessage, AtIcon, AtToast } from 'taro-ui';
import { releaseArticle } from "@/api/application/publicarticle";
import Header from '@/components/header';
import Return from '@/components/Return';
import SubmitOkModal from '@/components/SubmitOkModal';
import "taro-ui/dist/style/components/message.scss";
import "taro-ui/dist/style/components/image-picker.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/toast.scss";
import css from './index.module.less';
import "./index.less";

/**
 * 应用/发布文章
 */
export default function PublishArticle() {
  //表单各项的值
  const [userInfo, setUserInfo] = useState({});
  const [title, setTitle] = useState("");
  const [type, setType] = useState(1);
  const [source, setSource] = useState("");
  const [content, setContent] = useState("");
  //上传文件相关数据
  const [imgs, setImgs] = useState([]);
  const [files, setFiles] = useState([]);
  const [imgIds, setImgIds] = useState([]);
  const [fileIds, setFileIds] = useState([]);
  //提交成功弹窗的可见性
  const [submitOkVis, setSubmitOkVis] = useState(false);
  //加载中
  const [isOpened, setIsOpened] = useState(false);

  useEffect(() => {
    Taro.getStorage({
      key: 'userInfo',
      success: function (user) {
        setUserInfo(user.data);
        if (user.data.isAudited !== 1) {
          Taro.atMessage({
            'message': '您还未进行认证',
            'type': 'error',
            'duration': 2000
          });
        }
      }
    });
  }, []);

  useEffect(() => {
    if (imgs.length > 0) {
      if (imgIds.length < imgs.length) {
        uploadImgFiles(imgIds.length);
      }
      else if (imgIds.length === imgs.length) uploadExtraFiles(0);
    }
  }, [imgIds]);

  useEffect(() => {
    if (files.length > 0) {
      if (fileIds.length < files.length) {
        uploadExtraFiles(fileIds.length);
      }
      else if (fileIds.length === files.length) release();
    }
  }, [fileIds]);

  const imgOnChange = (tempImgs) => {
    const validFiles = tempImgs.filter(file => file.file.size / 1024 / 1024 < 1);
    if (validFiles.length !== tempImgs.length) tipMessage('文件大小不能超过 1M');
    if (validFiles.length <= 9) setImgs([...validFiles]);
    else tipMessage('附件最大上传数 9');
  };

  const fileOnChange = () => {
    Taro.chooseMessageFile({
      success: function (res) {
        const validFiles = res.tempFiles.filter(file => file.size / 1024 / 1024 < 1);
        if (validFiles.length !== res.tempFiles.length) tipMessage('文件大小不能超过 1M');
        if (files.length + validFiles.length <= 9) setFiles([...files, ...validFiles]);
        else tipMessage('附件最大上传数 9');
      }
    });
  };

  const fileRemove = (e, index) => {
    files.splice(index, 1);
    setFiles([...files]);
  };

  const tipMessage = (message) => {
    Taro.atMessage({
      'message': message,
      'type': 'warning',
      'duration': 2000
    });
  };

  const isValid = () => {
    if (title === "") {
      tipMessage('请填写标题');
      return false;
    }
    else if (title.length < 5) {
      tipMessage('标题长度不能小于5');
      return false;
    }
    else if (source === "") {
      tipMessage('请填写来源');
      return false;
    }
    else if (content === "") {
      tipMessage('请填写内容');
      return false;
    }
    else if (content.length < 200) {
      tipMessage('文章内容不能少于200字');
      return false;
    }
    return true;
  };

  function uploadImgFiles(index) {
    if (imgs.length > 0) {
      Taro.uploadFile({
        url: 'http://localhost:8082/oss/upload/dynamic_article_management/0/img',
        filePath: imgs[index].url,
        name: "file",
        success: function (resImg) {
          imgIds.push(JSON.parse(resImg.data).data.id);
          setImgIds([...imgIds]);
        },
      });
    }
    else uploadExtraFiles(0);
  }

  function uploadExtraFiles(index) {
    if (files.length > 0) {
      Taro.uploadFile({
        url: 'http://localhost:8082/oss/upload/dynamic_article_management/0/file',
        filePath: files[index].path,
        name: "file",
        success: function (resExtra) {
          fileIds.push(JSON.parse(resExtra.data).data.id);
          setFileIds([...fileIds]);
        },
      });
    }
    else release();
  }

  const release = () => {
    const { partyId } = userInfo;
    const info = {
      content, contributorId: partyId,
      fileIds, imgIds, source, title, type
    };
    releaseArticle(info).then(res => {
      if (res.code === 200) {
        setSubmitOkVis(true);
      }
      else {
        Taro.atMessage({
          'message': res.message,
          'type': 'error',
          'duration': 2000
        });
      }
    }).finally(() => { setIsOpened(false); });
  };

  const onSubmit = () => {
    if (isValid()) {
      setIsOpened(true);
      uploadImgFiles(0);
    }
  };

  const preView = () => {
    if (isValid()) {
      const { partyId, name, organizationName } = userInfo;
      const formData = {
        content, contributorId: partyId,
        files, imgs, source, title,
        type, name, organizationName
      };
      Taro.navigateTo({ url: `previewArticle/index?data=${JSON.stringify(formData)}` });
    }
  };

  return (
    <View className={css.home}>
      <Header message='发布文章' left='140px' />
      <Return />
      <AtForm className={css.form} onSubmit={onSubmit}>
        <AtMessage />
        <View className={css.formItem}>
          <AtInput
            name='title'
            title='文章标题'
            required
            value={title}
            maxLength={20}
            onChange={e => { setTitle(e); }}
            placeholder='请输入5字以上的文章标题'
          />
        </View>
        <View className={css.formItem}>
          <View className={`required ${css.lable}`}>文章类型</View>
          <View className={css.radioGroup}>
            <RadioGroup onChange={e => { setType(+e.detail.value); }}>
              <Radio className={css.radio} color='#DE270F' value={1} checked>党员先锋</Radio>
              <Radio className={css.radio} color='#DE270F' value={2}>基层风采</Radio>
              <Radio className={css.radio} color='#DE270F' value={4}>战斗堡垒</Radio>
            </RadioGroup>
          </View>
        </View>
        <View className={css.formItem}>
          <AtInput
            name='source'
            title='文章来源'
            required
            value={source}
            maxLength={20}
            onChange={e => { setSource(e); }}
            placeholder='例如 央视网'
          />
        </View>
        <View className={css.formItem}>
          <View className={`required ${css.lable}`}>文章内容</View>
          <AtTextarea
            value={content}
            onChange={e => { setContent(e); }}
            placeholder='请输入不少于200字的文章内容'
            maxLength={2000}
            count
            height={600}
          />
        </View>
        <View className={css.formItem}>
          <View className={css.lable}>上传图片:</View>
          <AtImagePicker
            files={imgs}
            onChange={imgOnChange}
            count={9}
            length={3}
            multiple
            mode='scaleToFill'
          />
        </View>
        <View className={css.formItem}>
          <View className={css.lable}>上传文件:</View>
          <View>
            <Button type='warn' plain size='mini' onClick={fileOnChange}>+ 上传文件</Button>
            {
              files.map((file, index) => (
                <View key={index} className={css.file}>
                  <AtIcon value='file-generic' size='18rpx' color='rgb(154,154,154)' />
                  {file.name.length > 9 ? `${file.name.slice(0, 9)}...` : file.name}
                  <AtIcon
                    value='trash'
                    size='18rpx'
                    color='rgb(154,154,154)'
                    onClick={e => fileRemove(e, index)}
                  />
                </View>
              ))
            }
            <View className={css.tip}>支持拓展名: .doc .docx .pdf .xslx...</View>
          </View>
        </View>
        <View className={css.buttonBox}>
          <Button plain className={css.submitBtn} formType='submit'>提交</Button>
          <Button plain className={css.previewBtn} onClick={preView}>预览</Button>
        </View>
      </AtForm>

      <SubmitOkModal
        visible={submitOkVis}
        setVisible={setSubmitOkVis}
        url='../../applaction/index'
        text='文章'
      />

      <AtToast isOpened={isOpened} text='上传数据中...' status='loading' duration={0} hasMask />
    </View>
  );
}